package com.dianrui.operation.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.dianrui.operation.Constant;
import com.dianrui.operation.R;
import com.dianrui.operation.adapter.AreaAdapter;
import com.dianrui.operation.bean.Area;
import com.dianrui.operation.bean.BikePointModel;
import com.dianrui.operation.event.AddPoint;
import com.dianrui.operation.event.MapScroll;
import com.dianrui.operation.event.MapUnScroll;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.LatLngBounds;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.PaletteView;
import com.google.gson.JsonObject;
import com.wx.wheelview.widget.WheelView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 新建停车点
 */
public class ChoosePointActivity extends BaseActivity implements AMapLocationListener, PaletteView.Callback {
    private String mTitles;
    private AMap aMap;
    private String misForBid = "0";
    private double lat, lng;
    public AMapLocationClient mLocationClient;
    public AMapLocationClientOption mLocationOption = null;
    private boolean isFirstLoc = true;
    private UiSettings mUiSettings;
    private List<Area> areasList = new ArrayList<>();
    private String areaId;
    private String areaName;
    private double centerPointLats, centerPointLngs;
    private LatLng latLng;
    private List<LatLng> templatLngList = new ArrayList<>();
    private List<LatLng> polygonlatLngLists = new ArrayList<>();
    private List<LatLng> mAreaPoints = new ArrayList<>();
    private List<BikePointModel> bikePointList = new ArrayList<>();
    private LatLng latLngs;
    private Polygon mCurrentpolygon;
    private Polygon mStoppolygon;



    @BindView(R.id.name)
    EditText showName;
    @BindView(R.id.input_layout)
    LinearLayout inputLayout;
    @BindView(R.id.number)
    EditText showNumber;
    @BindView(R.id.address)
    EditText showAddress;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.choose_address)
    TextView chooseAddress;//新建区域
    @BindView(R.id.cancel_area)
    TextView cancelArea;//取消区域
    @BindView(R.id.mapviews)
    MapView mapviews;
    @BindView(R.id.top_right)
    TextView topRight;
    @BindView(R.id.top_save)
    TextView topSave;
    @BindView(R.id.platteview)
    PaletteView platteview;
    @BindView(R.id.fram_layout)
    FrameLayout platteviewFramLayout;
    @BindView(R.id.switch_nostop)
    Switch switchNostop;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapviews.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapviews.onSaveInstanceState(outState);
    }


    @Override
    public int getContentViewId() {
        return R.layout.choose_point;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        platteview = new PaletteView(ChoosePointActivity.this);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mTitles = bundle.getString("title");
                title.setText(mTitles);
            }
        }
        if (aMap == null) {
            aMap = mapviews.getMap();
        }
        mUiSettings = aMap.getUiSettings();
        mUiSettings.setTiltGesturesEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);


        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。


        topSave.setVisibility(View.VISIBLE);
        topSave.setText(getString(R.string.save));
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(ChoosePointActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                ActivityCompat.requestPermissions(ChoosePointActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        } else {
            startLocation();
        }
        //TODO
        switchNostop.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //无论是否选中禁停区域都要把之前的多边形给移除掉
                if (mStoppolygon != null) {
                    mStoppolygon.remove();
                }
                if (mCurrentpolygon != null) {
                    mCurrentpolygon.remove();
                }
                if (isChecked) {
                    misForBid = "1";
                    PolygonOptions polygonOptions = new PolygonOptions();
                    polygonOptions.addAll(polygonlatLngLists);
                    polygonOptions.strokeWidth(4);
                    polygonOptions.strokeColor(Color.rgb(255, 0, 0));//相当于把多边形变了颜色
                    polygonOptions.fillColor(Color.argb(0, 0, 0, 0));
                    mStoppolygon=aMap.addPolygon(polygonOptions);

                } else {
                    misForBid = "0";
                    PolygonOptions polygonOptions = new PolygonOptions();
                    polygonOptions.addAll(polygonlatLngLists);
                    polygonOptions.strokeWidth(4);
                    polygonOptions.strokeColor(Color.rgb(64, 194, 134));
                    polygonOptions.fillColor(Color.argb(0, 0, 0, 0));
                    mCurrentpolygon=aMap.addPolygon(polygonOptions);

                }
            }
        });
    }

    @Override
    public void initData() {}

    //开始定位
    private void startLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }


    @Override
    protected void onResume() {
        super.onResume();
        mapviews.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapviews.onPause();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MapScroll scroll) {
        mUiSettings = aMap.getUiSettings();
        mUiSettings.setScrollGesturesEnabled(false);//禁止地图放大旋转等操作
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MapUnScroll mapUnScroll) {
        mUiSettings = aMap.getUiSettings();
        mUiSettings.setScrollGesturesEnabled(true);//不禁止地图放大旋转等操作
    }

    //画完路径在地图显示多边形
    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddPoint addPoint) {
        inputLayout.setVisibility(View.VISIBLE);
        //少了这句，我就这么感觉画完多边形这么别扭
        platteviewFramLayout.setVisibility(View.INVISIBLE);

        showNumber.setText("15");
        chooseAddress.setVisibility(View.GONE);
        cancelArea.setVisibility(View.VISIBLE);

        if (templatLngList != null) {
            templatLngList.clear();
        }
        if (polygonlatLngLists != null) {
            polygonlatLngLists.clear();
        }

        Projection projection = aMap.getProjection();
        for (int i = 0; i < addPoint.pointList.size(); i++) {
            latLng = projection.fromScreenLocation(new Point(addPoint.pointList.get(i).x, addPoint.pointList.get(i).y));//通过屏幕的坐标转换为高德坐标
            templatLngList.add(latLng);
            polygonlatLngLists.add(latLng);
        }

        if (switchNostop.isChecked()) {
            PolygonOptions polygonOptions = new PolygonOptions();
            polygonOptions.addAll(polygonlatLngLists);
            polygonOptions.strokeWidth(4);
            polygonOptions.strokeColor(Color.rgb(255, 0, 0));
            polygonOptions.fillColor(Color.argb(0, 0, 0, 0));
            mStoppolygon=aMap.addPolygon(polygonOptions);

        } else {
            PolygonOptions polygonOptions = new PolygonOptions();
            polygonOptions.addAll(polygonlatLngLists);
            polygonOptions.strokeWidth(4);
            polygonOptions.strokeColor(Color.rgb(64, 194, 134));
            polygonOptions.fillColor(Color.argb(0, 0, 0, 0));
            mCurrentpolygon=aMap.addPolygon(polygonOptions);

        }

        //坐标转地址
        LatLonPoint points = new LatLonPoint(latLng.latitude, latLng.longitude);
        GeocodeSearch geocodeSearch = new GeocodeSearch(ChoosePointActivity.this);
        // 第一个参数表示一个Latlng(经纬度)，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery regeocodeQuery = new RegeocodeQuery(points, 500, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(regeocodeQuery);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {

            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int rCode) {
                if (1000 == rCode) {
                    RegeocodeAddress address = regeocodeResult.getRegeocodeAddress();
                    showAddress.setText(address.getFormatAddress());
                    for (int i = 0; i < address.getPois().size(); i++) {
                        showName.setText(address.getPois().get(i).getTitle());
                        break;
                    }
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int rCode) {
            }
        });

        //获取多边形的中心点的经纬度
        centerPointLats = (LatLngBounds.getMinLatitude(polygonlatLngLists) + LatLngBounds.getMaxLatitude(polygonlatLngLists)) / 2;
        centerPointLngs = (LatLngBounds.getMinLongitude(polygonlatLngLists) + LatLngBounds.getMaxLongitude(polygonlatLngLists)) / 2;
    }


    @OnClick({R.id.back, R.id.top_save, R.id.choose_address, R.id.location, R.id.cancel_area})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.top_save://保存
                if (StringUtils.isEmpty(showName.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_name_error));
                    return;
                }
                if (StringUtils.isEmpty(showNumber.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_number_error));
                    return;
                }
                if (StringUtils.isEmpty(showAddress.getText().toString())) {
                    ToastUtil.showToast(getString(R.string.input_address_error));
                    return;
                }
                if (templatLngList.size() == 0) {
                    ToastUtil.showToast(getString(R.string.draw_area_error));
                    return;
                }
                subPoints(areaId);

                break;

            case R.id.location://定位
                if (lat == 0.0000 || lng == 0.0000) {
                    return;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(ChoosePointActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
                        aMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)));
                    } else {
                        ActivityCompat.requestPermissions(ChoosePointActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 3);
                    }
                } else {
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
                    aMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)));
                }
                break;

            case R.id.choose_address://新建区域
                if (switchNostop.isChecked()) {
                    if (null != templatLngList) {
                        templatLngList.clear();
                    }
                    if (null != polygonlatLngLists) {
                        polygonlatLngLists.clear();
                    }
                    if (mStoppolygon != null) {
                        mStoppolygon.remove();
                    }
                    if (mCurrentpolygon != null) {
                        mCurrentpolygon.remove();
                    }

                } else {
                    if (null != templatLngList) {
                        templatLngList.clear();
                    }
                    if (null != polygonlatLngLists) {
                        polygonlatLngLists.clear();
                    }
                    if (mStoppolygon != null) {
                        mStoppolygon.remove();
                    }
                    if (mCurrentpolygon != null) {
                        mCurrentpolygon.remove();
                    }
                }
                switchNostop.setChecked(false);
                if (StringUtils.isEmpty(areaId)) {//判断area是否为空，空的话先显示名称这几个输入框
                    if (null != templatLngList) {
                        templatLngList.clear();
                    }
                    if (null != polygonlatLngLists) {
                        polygonlatLngLists.clear();
                    }
                    inputLayout.setVisibility(View.VISIBLE);
                    platteviewFramLayout.setVisibility(View.GONE);
                    getAreas(lat, lng);
                } else {
                    inputLayout.setVisibility(View.GONE);
                    platteviewFramLayout.setVisibility(View.VISIBLE);//不是空的话直接显示画板view
                }

                break;

            case R.id.cancel_area://取消区域(把刚才画的清除)
                if (switchNostop.isChecked()) {
                    if (null != templatLngList) {
                        templatLngList.clear();
                    }
                    if (null != polygonlatLngLists) {
                        polygonlatLngLists.clear();
                    }
                    if (mStoppolygon != null) {
                        mStoppolygon.remove();
                    }
                    if (mCurrentpolygon != null) {
                        mCurrentpolygon.remove();
                    }

                } else {
                    if (null != templatLngList) {
                        templatLngList.clear();
                    }
                    if (null != polygonlatLngLists) {
                        polygonlatLngLists.clear();
                    }
                    if (mStoppolygon != null) {
                        mStoppolygon.remove();
                    }
                    if (mCurrentpolygon != null) {
                        mCurrentpolygon.remove();
                    }
                }
                switchNostop.setChecked(false);
                chooseAddress.setVisibility(View.VISIBLE);
                cancelArea.setVisibility(View.GONE);
                showName.setText("");
                showAddress.setText("");
                showNumber.setText("");

                platteviewFramLayout.setVisibility(View.GONE);//隐藏画板view
                break;
            default:
                break;

        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            lat = aMapLocation.getLatitude();
            lng = aMapLocation.getLongitude();
            if (isFirstLoc) {
                latLngs = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                getStation(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
                isFirstLoc = false;

            }
        }
    }

    //获取网点
    private void getStation(LatLng latLng) {
        JsonObject networksJsonobject = new JsonObject();
        networksJsonobject.addProperty("type_id", "2");
        networksJsonobject.addProperty("gps", latLng.longitude + "," + latLng.latitude);
        networksJsonobject.addProperty("radius", "0");//周边范围：默认1公里或者0公里,
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.GETNETWORK_BIKE, networksJsonobject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (bikePointList != null) {
                                bikePointList.clear();
                            }
                            if (mAreaPoints != null) {
                                mAreaPoints.clear();
                            }
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                JSONObject jsonObject2 = jsonObject.optJSONObject("area");
                                if (jsonObject.optString("data").equals("{}")) {
                                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 14));
                                } else {
                                    JSONArray gfixed_path = jsonObject.optJSONObject("area").optJSONArray("gfixed_path");
                                    if (gfixed_path.length() > 0) {
                                        for (int j = 0; j < gfixed_path.length(); j++) {
                                            JSONObject jsonObject3 = gfixed_path.optJSONObject(j);
                                            mAreaPoints.add(new LatLng(jsonObject3.optDouble("lat"), jsonObject3.optDouble("lng")));
                                        }
                                        if (mAreaPoints.size() > 0) {
                                            PolygonOptions polygonOptions = new PolygonOptions();
                                            polygonOptions.addAll(mAreaPoints);
                                            polygonOptions.strokeWidth(4);
                                            polygonOptions.strokeColor(Color.rgb(255, 0, 0));
                                            polygonOptions.fillColor(Color.argb(0, 0, 0, 0));
                                            aMap.addPolygon(polygonOptions);
                                        }
                                        com.amap.api.maps.model.LatLngBounds.Builder b = com.amap.api.maps.model.LatLngBounds.builder();

                                        for (LatLng latLng : mAreaPoints) {
                                            b.include(latLng);
                                        }
                                        com.amap.api.maps.model.LatLngBounds bounds = b.build();
                                        aMap.moveCamera(CameraUpdateFactory.newLatLngBoundsRect(bounds, 80, 80, 230, 260));
                                    }

                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        BikePointModel bikeModel = new BikePointModel();
                                        bikeModel.blat = jsonArray.optJSONObject(i).optDouble("glat");
                                        bikeModel.blng = jsonArray.optJSONObject(i).optDouble("glng");
                                        bikeModel.vehicle_number = jsonArray.optJSONObject(i).optString("vehicle_number");
                                        bikePointList.add(bikeModel);

                                        if ("1".equals(jsonArray.optJSONObject(i).optString("fixed_type"))) {
                                            List<LatLng> points = new ArrayList<>();
                                            if (points != null) {
                                                points.clear();
                                            }
                                            JSONArray jsonArray3 = jsonArray.optJSONObject(i).optJSONArray("fixed_path");
                                            if (jsonArray3.length() > 0) {
                                                for (int j = 0; j <= jsonArray3.length(); j++) {
                                                    if (j == jsonArray3.length()) {
                                                        JSONObject jsonObject1 = jsonArray3.optJSONObject(0);
                                                        points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                    } else {
                                                        JSONObject jsonObject1 = jsonArray3.optJSONObject(j);
                                                        points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                    }
                                                }

                                                if (points.size() < 2) {
                                                    return;
                                                }
                                                if (jsonArray.optJSONObject(i).optString("is_forbid").equals("1")) {
                                                    List<BitmapDescriptor> textureList = new ArrayList<>();
                                                    textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.nostop_img));

                                                    List<Integer> textureIndexs = new ArrayList<>();
                                                    textureIndexs.add(i);
                                                    List<LatLng> overLatlngList = new ArrayList<>(points);

                                                    PolylineOptions polylineOptions = new PolylineOptions();
                                                    polylineOptions.addAll(overLatlngList);
                                                    polylineOptions.width(4);
                                                    polylineOptions.setCustomTextureList(textureList);
                                                    polylineOptions.setCustomTextureIndex(textureIndexs);
                                                    polylineOptions.setDottedLine(true);
                                                    polylineOptions.setUseTexture(true);
                                                    aMap.addPolyline(polylineOptions);
                                                } else {
                                                    List<BitmapDescriptor> textureList = new ArrayList<>();
                                                    textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.customer_img));

                                                    List<Integer> textureIndexs = new ArrayList<>();
                                                    textureIndexs.add(i);
                                                    List<LatLng> overLatlngList = new ArrayList<>(points);

                                                    PolylineOptions polylineOptions = new PolylineOptions();
                                                    polylineOptions.addAll(overLatlngList);
                                                    polylineOptions.width(4);
                                                    polylineOptions.setCustomTextureList(textureList);
                                                    polylineOptions.setCustomTextureIndex(textureIndexs);
                                                    polylineOptions.setDottedLine(true);
                                                    polylineOptions.setUseTexture(true);
                                                    aMap.addPolyline(polylineOptions);
                                                }
                                            }
                                        } else if ("0".equals(jsonArray.optJSONObject(i).optString("fixed_type"))) {
                                            int networkRange = jsonArray.optJSONObject(i).optInt("network_range");
                                            aMap.addCircle(new CircleOptions()
                                                    .center(new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng))
                                                    .radius(networkRange)
                                                    .fillColor(Color.argb(46,64,194,134)).strokeWidth(4).strokeColor(Color.argb(46,64,194,134)));
                                        }
                                    }
                                }
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }

    //获取附近区域
    private void getAreas(double latitude, double longitude) {
        showLoadingDialog("请稍等");
        JsonObject networks = new JsonObject();
        networks.addProperty("lng", longitude);
        networks.addProperty("lat", latitude);
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.AREA, networks.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                 dismissLoadingDialog();
                                if (null != areasList && areasList.size() > 0) {
                                    areasList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        Area area = new Area();
                                        area.area_id = jsonArray.optJSONObject(i).optString("area_id");
                                        area.area_name = jsonArray.optJSONObject(i).optString("area_name");
                                        areasList.add(area);
                                    }
                                    areaId = areasList.get(0).area_id;

                                    loadBottomDialog();
                                }
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                 dismissLoadingDialog();
                                ToastUtil.showToast(getString(R.string.area_error_hint));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                 dismissLoadingDialog();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                 dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void loadBottomDialog() {
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(ChoosePointActivity.this);
        View view = LayoutInflater.from(ChoosePointActivity.this).inflate(R.layout.layout_area_dialog, null);
        final WheelView wheelView = view.findViewById(R.id.wheelview);
        final AreaAdapter adapter = new AreaAdapter(ChoosePointActivity.this, areasList);
        wheelView.setWheelAdapter(adapter);
        wheelView.setWheelData(areasList);
        WheelView.WheelViewStyle style = new WheelView.WheelViewStyle();
        style.selectedTextSize = 16;
        style.textSize = 16;
        style.textColor = Color.argb(255, 125, 125, 125); // 文本颜色 灰色
        style.selectedTextColor = Color.BLACK; // 选中文本颜色 黑色
        style.textAlpha = 0.5f;  // 文本透明度(0f ~ 1f)
        style.selectedTextZoom = 1.5f; // 选中文本放大倍数
        wheelView.setStyle(style);
        wheelView.setSkin(WheelView.Skin.Holo);
        wheelView.setWheelClickable(true);
        wheelView.setOnWheelItemSelectedListener(new WheelView.OnWheelItemSelectedListener() {
            @Override
            public void onItemSelected(int position, Object o) {
                Area area = areasList.get(position);
                areaId = area.area_id;
            }
        });
        TextView sure = view.findViewById(R.id.tv_confirm);//确定
        TextView cancel = view.findViewById(R.id.tv_cancel);//取消
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomSheetDialog.dismiss();
                AlertDialog.Builder builder1 = new AlertDialog.Builder(ChoosePointActivity.this, R.style.RcDialog);
                View view2 = LayoutInflater.from(ChoosePointActivity.this).inflate(R.layout.dialog_choosepoint, null);
                final AlertDialog dialog1 = builder1.create();
                dialog1.setView(view2);
                dialog1.show();
                final TextView yes_dialog = view2.findViewById(R.id.yes_dialog_ask);
                yes_dialog.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog1.dismiss();
                        if (templatLngList != null) {
                            templatLngList.clear();
                        }
                        if (polygonlatLngLists != null) {
                            polygonlatLngLists.clear();
                        }
                        inputLayout.setVisibility(View.GONE);
                        platteviewFramLayout.setVisibility(View.VISIBLE);
                    }
                });

            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomSheetDialog.dismiss();
                areaId = "";
                if (templatLngList != null) {
                    templatLngList.clear();
                }
                if (polygonlatLngLists != null) {
                    polygonlatLngLists.clear();
                }
                inputLayout.setVisibility(View.VISIBLE);
                platteviewFramLayout.setVisibility(View.GONE);
            }
        });

        if (bottomSheetDialog != null && bottomSheetDialog.isShowing()) {
            return;
        }
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCancelable(false);
        bottomSheetDialog.setCanceledOnTouchOutside(false);
        bottomSheetDialog.show();
    }

    @Override
    public void onUndoRedoStatusChanged() {}

    //保存停车区
    private void subPoints(String areaId) {
        String substring = "";
        for (int i = 0; i < templatLngList.size(); i++) {
            if (i == 0) {
                double lat = templatLngList.get(i).latitude;
                double longitude = templatLngList.get(i).longitude;
                String lats = Double.valueOf(lat).toString();
                String lngs = Double.valueOf(longitude).toString();
                substring += lngs + "," + lats;
            } else {
                double lat = templatLngList.get(i).latitude;
                double longitude = templatLngList.get(i).longitude;
                String lats = Double.valueOf(lat).toString();
                String lngs = Double.valueOf(longitude).toString();
                substring += "," + lngs + "," + lats;
            }
        }
        showLoadingDialog("正在提交中...");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", showName.getText().toString().trim());//名称
            jsonObject.put("allow_number", showNumber.getText().toString().trim());//车位（数量）
            jsonObject.put("city_path", showAddress.getText().toString());//网点地址
            jsonObject.put("fixed_path", substring);//画的区域转换成高德坐标，以逗号形式上传如121.51191980387894,31.302381017991177,121.51330918812488,31.299515104484346,
            jsonObject.put("is_forbid", misForBid);//是否是禁停区：0否，1是
            jsonObject.put("fixed_type", "1");//fixed_type：是否是多变形形：固定传1
            jsonObject.put("lat", centerPointLats);//中心点经度
            jsonObject.put("lng", centerPointLngs);//中心点纬度
            jsonObject.put("area_id", areaId);//区域id必传
            XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.INSERT_NETWORK, jsonObject.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String result) {
                    if (!StringUtils.isEmpty(result)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(result);
                            if (null != jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                     dismissLoadingDialog();
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    showAddress.setText("");
                                    showName.setText("");
                                    showNumber.setText("");
                                    platteviewFramLayout.setVisibility(View.GONE);
                                    chooseAddress.setVisibility(View.VISIBLE);
                                    cancelArea.setVisibility(View.GONE);
                                    getStation(latLngs);
                                } else if ("1001".equals(jsonObject.optString("status"))) {
                                     dismissLoadingDialog();
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                } else if ("1002".equals(jsonObject.optString("status"))) {
                                     dismissLoadingDialog();
                                    spUtils.clear();
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    JumpActivitys(LoginActivity.class);
                                    finish();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                     dismissLoadingDialog();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startLocation();
                }
                break;

            default:
                break;

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapviews.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        if (templatLngList != null) {
            templatLngList.clear();
            templatLngList=null;
        }
        if (polygonlatLngLists != null) {
            polygonlatLngLists.clear();
            polygonlatLngLists=null;
        }
    }
}
